package org.mycub.server.parser;

import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.json.JSONObject;
import org.mycub.server.data.models.VCUBStation;
import org.mycub.server.datainserter.VCUBStationsInserter;
import org.mycub.server.datainserter.factory.VCUBStationsInserterFactory;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;


public class CollectVCUBStation extends CollectItem{

	private VCUBStation vCUBStation;

	public CollectVCUBStation(){
		this.setVCUBStation(new VCUBStation());
	}

	public void collect(SimpleFeature feature){		

		String ident = (String) feature.getAttribute(0);
		Point point = (Point) feature.getAttribute(1);
		String name = (String) feature.getAttribute(2);
		String state = (String) feature.getAttribute(3);
		String nbPlaces = (String) feature.getAttribute(4);
		String nbVCUBs = (String) feature.getAttribute(5);
		String heure = (String) feature.getAttribute(6);
		
		Geometry env = point.getEnvelope();
		try {
			
			env = JTS.toGeographic(env,CRS.decode("EPSG:3945"));
			
		} catch ( TransformException | FactoryException e ) {
			e.printStackTrace();
		}

		VCUBStation vCUBStationCollected = new VCUBStation();
		vCUBStationCollected.setId(ident);
		vCUBStationCollected.setLongitude(env.getCoordinates()[0].x);
		vCUBStationCollected.setLatitude(env.getCoordinates()[0].y);
		vCUBStationCollected.setName(name);
		vCUBStationCollected.setState(state);
		vCUBStationCollected.setNbPlaces(Integer.parseInt(nbPlaces));
		vCUBStationCollected.setNbVCUBs(Integer.parseInt(nbVCUBs));
		vCUBStationCollected.setHeure(heure);

		this.setVCUBStation(vCUBStationCollected);

		System.out.println("collected VCUB station : " + vCUBStationCollected.getName() + 
				" id = " + vCUBStationCollected.getId());

		saveVCUBStation(vCUBStationCollected);
	}

	public void saveVCUBStation(VCUBStation vCUBStationCollected){
		VCUBStationsInserter vCUBStationsInserter = new VCUBStationsInserterFactory().createVCUBStationsInserter();
		vCUBStationsInserter.save(vCUBStationCollected);
	}

	public VCUBStation getVCUBStation() {
		return vCUBStation;
	}

	public void setVCUBStation(VCUBStation vCUBStation) {
		this.vCUBStation = vCUBStation;
	}

	@Override
	public void collect(JSONObject json) {
	}
}
